<template>
  <div class="main-container">
    <!-- 左侧地图区域 -->
    <div class="map-section">
      <MapContainer ref="mapContainer" />
    </div>

    <!-- 右侧控制面板 -->
    <div class="control-panel">
      <div class="panel-header">
        <h2>物流路径规划</h2>
      </div>

      <div class="panel-content">
        <!-- 物流信息功能 -->
        <div class="control-group">
          <h3>物流信息</h3>
          <div class="input-group">
            <el-input
                v-model="shipAddress"
                placeholder="请输入发货地址"
                clearable
                @keyup.enter="geocodeAndPlan"
            />
          </div>
          <div class="input-group">
            <el-input
                v-model="receiveAddress"
                placeholder="请输入收货地址"
                clearable
                @keyup.enter="geocodeAndPlan"
            />
          </div>
        </div>

        <!-- 发货地信息显示 -->
        <div class="control-group" v-if="startPointInfo">
          <h3>发货地</h3>
          <div class="point-info">
            <p><strong>地址:</strong> {{ startPointInfo.address }}</p>
          </div>
        </div>

        <!-- 收货地信息显示 -->
        <div class="control-group" v-if="destinationPointInfo">
          <h3>收货地</h3>
          <div class="point-info">
            <p><strong>地址:</strong> {{ destinationPointInfo.address }}</p>
          </div>
        </div>

        <!-- 物流信息显示 -->
        <div class="control-group" v-if="routeInfo">
          <h3>物流信息</h3>
          <div class="route-info">
            <p><strong>预计到达时间:</strong> {{ routeInfo.estimatedArrival }}</p>
          </div>
        </div>

        <!-- 发货状态显示 -->
        <div class="control-group" v-if="isShipped">
          <div class="route-info">
            <p><strong>发货状态:</strong> 已发货</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue'
import {ElMessage} from 'element-plus'
import MapContainer from './MapContainer.vue'

// 接收订单信息属性
const props = defineProps({
  orderInfo: {
    type: Object,
    default: null
  },
  shipAddress: {
    type: String,
    default: ''
  },
  receiveAddress: {
    type: String,
    default: ''
  }
})

// 响应式数据
const startPointInfo = ref(null) // 发货地信息
const destinationPointInfo = ref(null) // 收货地信息
const isAnimating = ref(false) // 是否正在播放动画
const routeInfo = ref(null) // 物流信息
const isPlanning = ref(false) // 是否正在规划路径
const isShipped = ref(false) // 是否已发货

// 地址输入数据
const shipAddress = ref('')
const receiveAddress = ref('')

// 地图相关引用
const mapContainer = ref(null)
let map = null
let geocoder = null

// 监听传入的发货地址和收货地址
watch(() => [props.shipAddress, props.receiveAddress], ([newShipAddr, newReceiveAddr]) => {
  if (newShipAddr) {
    shipAddress.value = newShipAddr
  }
  if (newReceiveAddr) {
    receiveAddress.value = newReceiveAddr
  }

  // 如果两个地址都存在，则自动规划路径
  if (newShipAddr && newReceiveAddr) {
    setTimeout(() => {
      geocodeAndPlan()
    }, 500)
  }
}, {immediate: true})

// 等待地图加载完成
const waitForMap = () => {
  return new Promise((resolve) => {
    const checkMap = () => {
      if (mapContainer.value && mapContainer.value.getMap()) {
        resolve(mapContainer.value.getMap())
      } else {
        setTimeout(checkMap, 100)
      }
    }
    checkMap()
  })
}

// 初始化地图插件
const initMapPlugins = async () => {
  try {
    map = await waitForMap()

    // 加载地理编码插件
    window.AMap.plugin(['AMap.Geocoder'], () => {
      geocoder = new window.AMap.Geocoder({
        city: '全国'
      })
      console.log('Geocoder插件加载成功')
    })
  } catch (error) {
    console.error('地图插件初始化失败:', error)
    ElMessage.error('地图插件初始化失败: ' + error.message)
  }
}

// 地理编码并规划路径
const geocodeAndPlan = async () => {
  if (!shipAddress.value || !receiveAddress.value) {
    ElMessage.warning('请输入发货地址和收货地址')
    return
  }

  if (!geocoder) {
    ElMessage.error('地理编码服务未加载完成')
    return
  }

  isPlanning.value = true

  try {
    // 地理编码发货地址
    const shipLocation = await new Promise((resolve, reject) => {
      geocoder.getLocation(shipAddress.value, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          resolve(result.geocodes[0].location)
        } else {
          reject(new Error('发货地址查询失败'))
        }
      })
    })

    // 地理编码收货地址
    const receiveLocation = await new Promise((resolve, reject) => {
      geocoder.getLocation(receiveAddress.value, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          resolve(result.geocodes[0].location)
        } else {
          reject(new Error('收货地址查询失败'))
        }
      })
    })

    // 在地图上设置起点和终点标记
    if (mapContainer.value) {
      // 清除之前的标记
      mapContainer.value.clearMarkers()

      // 设置发货地标记
      const startPoint = mapContainer.value.addStartMarker(shipLocation.lng, shipLocation.lat)
      const startAddress = await getAddressFromLngLat({lng: shipLocation.lng, lat: shipLocation.lat})
      startPointInfo.value = {
        lng: startPoint.lng,
        lat: startPoint.lat,
        address: startAddress
      }

      // 设置收货地标记
      const destinationPoint = mapContainer.value.addDestinationMarker(receiveLocation.lng, receiveLocation.lat)
      const destinationAddress = await getAddressFromLngLat({lng: receiveLocation.lng, lat: receiveLocation.lat})
      destinationPointInfo.value = {
        lng: destinationPoint.lng,
        lat: destinationPoint.lat,
        address: destinationAddress
      }

      // 规划路径
      await planRoute()

      // 重置发货状态
      isShipped.value = false
    }
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    isPlanning.value = false
  }
}

// 规划路线
const planRoute = async () => {
  try {
    const result = await mapContainer.value.planDrivingRoute(
        {lng: startPointInfo.value.lng, lat: startPointInfo.value.lat},
        {lng: destinationPointInfo.value.lng, lat: destinationPointInfo.value.lat}
    );

    // 使用高德地图返回的路线距离计算预计到达时间
    if (result.routes && result.routes.length > 0) {
      const route = result.routes[0];
      const distance = route.distance / 1000; // 转换为公里

      // 根据距离计算预计到达时间
      let estimatedArrival = '';
      if (distance < 50) {
        estimatedArrival = '第二天到达';
      } else if (distance < 300) {
        estimatedArrival = '三天后到达';
      } else if (distance < 500) {
        estimatedArrival = '五天后到达';
      } else {
        estimatedArrival = '七天后到达';
      }

      routeInfo.value = {
        estimatedArrival: estimatedArrival
      };

      // 规划路线后自动运行小车模拟动画
      setTimeout(() => {
        shipGoods();
      }, 1000);
    }

  } catch (error) {
    console.error('路线规划失败:', error);
    ElMessage.error('路线规划失败: ' + error.message);
  }
}

// 发货操作 - 启动小车动画
const shipGoods = async () => {
  isAnimating.value = true;
  try {
    await mapContainer.value.startTrackAnimation();
    isShipped.value = true;
    ElMessage.success('货物已发货，正在运输中...');
  } catch (error) {
    console.error('运输动画播放失败:', error);
    ElMessage.error('运输动画播放失败: ' + error.message);
  } finally {
    isAnimating.value = false;
  }
}

// 逆地理编码获取地址
const getAddressFromLngLat = (point) => {
  return new Promise((resolve) => {
    if (!geocoder) {
      window.AMap.plugin('AMap.Geocoder', () => {
        geocoder = new window.AMap.Geocoder()
        geocoder.getAddress([point.lng, point.lat], (status, result) => {
          if (status === 'complete' && result.regeocode) {
            resolve(result.regeocode.formattedAddress)
          } else {
            resolve('地址解析失败')
          }
        })
      })
    } else {
      geocoder.getAddress([point.lng, point.lat], (status, result) => {
        if (status === 'complete' && result.regeocode) {
          resolve(result.regeocode.formattedAddress)
        } else {
          resolve('地址解析失败')
        }
      })
    }
  })
}

// 组件挂载后初始化地图插件
onMounted(() => {
  initMapPlugins()
})
</script>

<style scoped>
.main-container {
  display: flex;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.map-section {
  flex: 1;
  height: 100%;
  position: relative;
}

.control-panel {
  width: 350px;
  height: 100%;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  padding: 20px;
  background: linear-gradient(135deg, #0e88eb 100%, #ffffff 100%);
  color: white;
  flex-shrink: 0;
}

.panel-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  text-align: center;
}

.panel-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.control-group {
  margin-bottom: 25px;
}

.control-group h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.input-group .el-input {
  width: 100%;
}

.point-info {
  margin-top: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.point-info p {
  margin: 5px 0;
}

.route-info {
  margin-top: 15px;
  padding: 10px;
  background: #e6f7ff;
  border-radius: 4px;
  font-size: 14px;
  border-left: 4px solid #1890ff;
}

.route-info p {
  margin: 5px 0;
}

/* 滚动条样式 */
.poi-list::-webkit-scrollbar {
  width: 6px;
}

.poi-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.poi-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.poi-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    flex-direction: column;
  }

  .map-section {
    height: 60vh;
  }

  .control-panel {
    width: 100%;
    height: 40vh;
  }
}
</style>
